<template>
  <el-form ref="ruleForm" :model="ruleForm" :rules="rules"
           label-width="75px" @keydown.enter.native="submitForm">

    <el-form-item ref="username" label="用户名" prop="username">
      <el-input v-model="ruleForm.username" type="text"></el-input>
    </el-form-item>

    <el-form-item label="密码" prop="pass">
      <el-input v-model="ruleForm.pass" autocomplete="off"
                show-password type="password"></el-input>
    </el-form-item>

    <el-form-item label="确认密码" prop="checkPass">
      <el-input v-model="ruleForm.checkPass" autocomplete="off" type="password"></el-input>
    </el-form-item>

    <el-form-item label="邮箱" prop="mail">
      <el-input v-model="ruleForm.mail" type="text"></el-input>
    </el-form-item>

    <el-form-item label="验证码" prop="code">
      <el-input v-model="ruleForm.code" style="width: 50%" type="text"></el-input>
      <el-button id="sendBtn" :disabled="isSending || count > 0" plain
                 type="success" @click="sendMail">
        <i v-show="isSending" class="el-icon-loading"></i>
        <span :class="{wordTips: count > 0}">{{sendTipText}}</span>
      </el-button>
    </el-form-item>

    <el-form-item>
      <el-button-group>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button style="margin-left: 15%" @click="resetForm">重置</el-button>
      </el-button-group>
    </el-form-item>
  </el-form>
</template>

<script>
import encrypt from "../mixin/encrypt";
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Register',
  data() {
  const validateName = async (rule, value, callback) => {
      value = value.trim();
      if (value === '') {
        callback(new Error('用户名不能为空'));
      } else {
        const reg = /^[\w\u4e00-\u9fa5]{6,12}$/;
        if (!reg.test(value)) {
          callback(new Error('请输入仅包含中文、数字、英文字母的6-12位用户名'));
        } else {
          try {
            const res = await this.$axios.get(this.$store.state.serverUrl+'/api/checkName', {
              params: {username: this.ruleForm.username}
            });
            if (res.data.status !== 0) {
              callback(new Error('用户名已存在'));
            } else callback();
          } catch (err) {
            await this.$alert(err.message, '网络连接出错')
            callback(new Error('请稍后重试'))
          }
        }
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'));
      } else {
        const reg = /^\w{8,16}$/;
        if (!reg.test(value)) {
          callback(new Error('请输入仅包含数字和英文字母在内的8-16为密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    const validateMail = async (rule, value, callback) => {
      value = value.trim();
      if (value === '') {
        callback(new Error('请输入邮箱账号'));
      } else {
        const reg = /^[\w\u4e00-\u9fa5-]+@\w+\.+\w{2,}$/g;
        if (!reg.test(value)) {
          callback(new Error('请输入有效的邮箱地址'));
        } else {
          try {
            const res = await this.$axios.get(this.$store.state.serverUrl+'/api/checkMail', {
              params: {mail: this.ruleForm.mail}
            });
            if (res.data.status !== 0) {
              callback(new Error('该邮箱已被注册'));
            } else callback();
          } catch (err) {
            await this.$alert(err.message, '网络连接出错')
            callback(new Error('请稍后重试'))
          }
        }
      }
    };
    const validateCode = async (rule, value, callback) => {
      value = value.trim();
      if (value === '') {
        callback(new Error('请输入验证码'));
      } else {
        try {
          const res = await this.$axios.get(this.$store.state.serverUrl+'/api/verify', {
            params: {address: this.ruleForm.mail, ver: this.ruleForm.code}
          });
          if (res.data.status !== 0) {
            callback(new Error(res.data.msg));
          } else callback();
        } catch (err) {
          await this.$alert(err.message, '网络连接出错')
          callback(new Error('请稍后重试'))
        }
      }
    }
    return {
      ruleForm: {
        username: '',
        pass: '',
        checkPass: '',
        mail: '',
        code: '',
      },
      rules: {
        username: [{ validator: validateName, trigger: 'blur' }],
        pass: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }],
        mail: [{ validator: validateMail, trigger: 'blur' }],
        code: [{ validator: validateCode, trigger: 'none' }],
      },
      count: 0,
      isSending: false,
    };
  },
  computed: {
    sendTipText() {
      if (this.isSending) return '发送中……'
      if (this.count > 0) return `重新发送 (${this.count}s)`
      else return '发送验证码'
    }
  },
  mixins: [encrypt],
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          await this.$alert('请检查输入内容', '输入验证不通过')
          return false
        } else {
          try {
            const encrypted = await this.encrypt(this.ruleForm.pass);
            try {
              const res = await this.$axios.post(this.$store.state.serverUrl + '/api/register',
                  { username:this.ruleForm.username.trim(),
                    password:encrypted,
                    mail: this.ruleForm.mail.trim()});
              if (res.data.status !== 0) {
                await this.$alert(res.data.msg, '注册失败')
              } else {
                this.$store.state.username = this.ruleForm.username.trim();
                this.$store.state.isFormDialogVis = false;
                localStorage.setItem('token', res.data['msg']);
                this.$store.commit('updateToken');
                this.$message.success('注册成功！');
              }
            } catch (err) {
              await this.$alert(err.message, '网络连接出错')
            }
          } catch (err) {
            await this.$alert(err.message, '加密失败');
          }
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
    countDown() {
      if (this.count > 0) {
        this.count--;
        setTimeout(this.countDown, 1000);
      }
    },
    sendMail() {
      this.isSending = true;
      this.$refs.ruleForm.validateField('mail', err => {
        if (err) {
          this.$alert(err, '提示');
          this.isSending = false;
        }
        else {
          this.$axios.get(this.$store.state.serverUrl+'/api/sendMail', {
            params: {mail: this.ruleForm.mail}
          }).then(res => {
            this.isSending = false;
            if (res.data.status !== 0) {
              this.$alert(res.data.msg, '验证码发送失败')
            } else {
              this.$message.success('验证码已发送');
              this.count = 61;
              this.countDown();
            }
          }).catch(err => {
            this.$alert(err.message, '网络连接出错');
            this.isSending = false;
          })
        }
      })
    }
  },
  mounted() {
    this.$bus.$on('clearRegValRes', () => this.$refs.ruleForm.clearValidate());
    this.$bus.$on('resetRegForm', () => this.resetForm());
  },
  beforeDestroy() {
    this.$bus.$off('clearRegValRes');
    this.$bus.$off('resetRegForm', () => this.resetForm());
  }
}
</script>

<style lang="scss" scoped>
  .wordTips {
    font-style: italic;
    color: darkgray;
  }
  .el-button-group {
    width: 100%;
    .el-button {
      width: 40%;
    }
  }
  #sendBtn {
    position: relative;
    left: 50%;
    transform: translateX(-100%);
  }
</style>